<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>首页</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <link rel="stylesheet" href="/statics/css/global.css">
    <link rel="stylesheet" href="/statics/css/index.css">
    <link rel="stylesheet" href="/statics/css/tab.css">
    <link rel="stylesheet" href="/statics/css/myPagination.css">
    <script src="/statics/js/axios.min.js"></script>
    <style>
        body,
        html {
            margin: 0;
            padding: 0;
            height: 100%;
        }

        .page-wrapper {
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        #app {
            flex-grow: 1;
        }

        .footer {
            background-color: #f1f1f1;
            padding: 20px;
            text-align: center;
            width: 100%;
            position: relative;
        }

        .footer-line {
            color: #888;
        }

        .chat-container {
            display: flex;
            flex-direction: column;
            height: 80vh;
            width: 80vw;
            max-width: 600px;
            border: 1px solid #ccc;
            border-radius: 10px;
            overflow: hidden;
            background-color: #fff;
        }

        .chat-window {
            flex: 1;
            padding: 10px;
            overflow-y: auto;
            background-color: #f4f4f9;
            position: relative;
        }

        .chat-message {
            display: flex;
            margin-bottom: 10px;
            align-items: flex-start;
        }

        .message-left {
            flex-direction: row;
        }

        .message-right {
            flex-direction: row-reverse;
        }

        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #007bff;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
            font-weight: bold;
            margin: 0 10px;
        }

        .message-bubble {
            max-width: 70%;
            padding: 10px;
            border-radius: 20px;
            background-color: #007bff;
            color: white;
            word-wrap: break-word;
        }

        .message-left .message-bubble {
            background-color: #e4e6eb;
            color: black;
        }

        .chat-input {
            display: flex;
            padding: 10px;
            border-top: 1px solid #ccc;
            background-color: #fff;
        }

        .chat-input input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 20px;
            outline: none;
        }

        .chat-input button {
            margin-left: 10px;
            padding: 10px 20px;
            border: none;
            background-color: #007bff;
            color: white;
            border-radius: 20px;
            cursor: pointer;
            outline: none;
        }

        .chat-input button:hover {
            background-color: #0056b3;
        }


        .loader {
            position: relative;
            width: 2.5em;
            height: 2.5em;
            transform: rotate(165deg);
        }

        .loader:before,
        .loader:after {
            content: "";
            position: absolute;
            top: 50%;
            left: 50%;
            display: block;
            width: 0.5em;
            height: 0.5em;
            border-radius: 0.25em;
            transform: translate(-50%, -50%);
        }

        .loader:before {
            animation: before8 2s infinite;
        }

        .loader:after {
            animation: after6 2s infinite;
        }

        @keyframes before8 {
            0% {
                width: 0.5em;
                box-shadow: 1em -0.5em rgba(225, 20, 98, 0.75), -1em 0.5em rgba(111, 202, 220, 0.75);
            }

            35% {
                width: 2.5em;
                box-shadow: 0 -0.5em rgba(225, 20, 98, 0.75), 0 0.5em rgba(111, 202, 220, 0.75);
            }

            70% {
                width: 0.5em;
                box-shadow: -1em -0.5em rgba(225, 20, 98, 0.75), 1em 0.5em rgba(111, 202, 220, 0.75);
            }

            100% {
                box-shadow: 1em -0.5em rgba(225, 20, 98, 0.75), -1em 0.5em rgba(111, 202, 220, 0.75);
            }
        }

        @keyframes after6 {
            0% {
                height: 0.5em;
                box-shadow: 0.5em 1em rgba(61, 184, 143, 0.75), -0.5em -1em rgba(233, 169, 32, 0.75);
            }

            35% {
                height: 2.5em;
                box-shadow: 0.5em 0 rgba(61, 184, 143, 0.75), -0.5em 0 rgba(233, 169, 32, 0.75);
            }

            70% {
                height: 0.5em;
                box-shadow: 0.5em -1em rgba(61, 184, 143, 0.75), -0.5em 1em rgba(233, 169, 32, 0.75);
            }

            100% {
                box-shadow: 0.5em 1em rgba(61, 184, 143, 0.75), -0.5em -1em rgba(233, 169, 32, 0.75);
            }
        }

        .loading {
            position: relative;
            bottom: -20px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .chat-modal {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            /* 半透明背景 */
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .chat-container {
            display: flex;
            flex-direction: column;
            height: 80vh;
            width: 80vw;
            max-width: 600px;
            border: 1px solid #ccc;
            border-radius: 10px;
            overflow: hidden;
            background-color: #fff;
        }

        .chat-modal:hover {
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div class="page-wrapper">
        <nav class="nav-bar-holder" id="nav">
            <div class="nav-bar" id="nav-bar">
                <div class="logo-box">
                    <a href="http://localhost:8080/index" class="blog-title ta-c">
                        <img style="vertical-align: top;" alt="logo" src="/statics/images/logo.png" /></a>
                </div>
                <div class="nb-a-holder" id="home">
                    <a id="active" class="nb-a ta-c" href="index">首页</a>
                </div>
                <div class="nb-a-holder">
                    <a class="nb-a ta-c" href="/category.html">分类</a>
                </div>
                <div class="nb-a-holder">
                    <a :href="'/personInfo/' + (personInfo.userId || '')" class="nb-a ta-c">个人信息</a>
                </div>
                <div class="nb-a-holder-last">
                    <div class="nb-a-holder-small">
                        <a class="a-login" @click="logout" style="cursor: pointer;">注销</a>
                    </div>
                </div>
            </div>
        </nav>
        <div id="app">
            <el-container class="big-container" id="particles-js">
                <div class="article">
                    <div id="article-holder" class="left-holder">
                        <div id="article-holder" style="width: 100%; float: left" v-infinite-scroll="load" gutter="20">
                            <div v-if="blogs.length">
                                <div class="article-box" span="6" :offset="2" v-for="(blog, index) in blogs"
                                    :key="blog.id">
                                    <div class="ab-content">
                                        <a class="article-img-box" :href="'/blog/' + blog.blogId">
                                            <img class="lazy-image article-img" data-src="" alt=""
                                                :src="blog.img || '/statics/images/article.jpg'">
                                        </a>
                                        <div class="article-title">
                                            <a :href="'/blog/' + blog.blogId">
                                                {{ blog.title || '暂无标题' }}
                                            </a>
                                        </div>
                                        <div class="article-detail-box c-666">
                                            <a :href="'/blog/' + blog.blogId">
                                                {{ blog.content }}
                                            </a>
                                        </div>
                                        <span class="article-tail-box">
                                            <i class="fl"
                                               style="background-image: url('/statics/images/looks.svg')"></i>
                                            <span class="read-number c-999 fl">{{ blog.readed }}</span>
                                            <span class="comment-number c-999 fl"
                                                  v-if="blog.typeId === 1">&nbsp;&nbsp;手机</span>
                                            <span class="comment-number c-999 fl"
                                                  v-else-if="blog.typeId === 2">&nbsp;&nbsp;电脑</span>
                                            <span class="comment-number c-999 fl"
                                                  v-else-if="blog.typeId === 3">&nbsp;&nbsp;测评</span>
                                              <span class="comment-number c-999 fl"
                                                    v-else-if="blog.typeId === 4">&nbsp;&nbsp;AI</span>
                                               <span class="comment-number c-999 fl"
                                                     v-else-if="blog.typeId === 5">&nbsp;&nbsp;鸿蒙</span>
                                               <span class="comment-number c-999 fl"
                                                     v-else-if="blog.typeId === 6">&nbsp;&nbsp;苹果</span>
                                                <span class="comment-number c-999 fl" v-else>&nbsp;&nbsp;微软</span>
                                            <span class="article-date c-999">{{ blog.createDate | dateFormate }}</span>
                                            <span class="article-author one-line-overflow c-999">{{ blog.authorName
                                                }}</span>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div v-else>没有找到相关内容。</div>
                        </div>
                        <el-pagination class="pagination fl" id="pagination" v-if="pageParam.totalSize > 0"
                            :current-page="pageParam.current" :page-size="pageParam.size" :total="pageParam.totalNumber"
                            @current-change="handlePageChange" layout="total, prev, pager, next, jumper">
                        </el-pagination>
                    </div>
                    <div class="right-holder">
                        <div class="column-container">
                            <ul class="column_box" id="like-box">
                                <li class="column-title">
                                    <span class="at-sort b-b-ece fl"><a
                                            class="at-sort-comment-a c-666 fl">信息栏</a></span>
                                </li>
                                <li class="person-img-li">
                                    <a :href="'/personInfo/' + (personInfo.userId || '')">
                                        <el-image id="person-img" style="width: 80px; height: 80px;"
                                            :src="personInfo.avatar"></el-image>
                                    </a>
                                </li>
                                <li class="person-intro-detail gradient-text">
                                    <h1>{{personInfo.nickname }}</h1>
                                </li>
                                <li class="person-intro-detail">
                                    <h3>网站简介：OMT科技论坛</h3>
                                </li>
                                <li class="person-intro-detail">
                                    <h3>所在地：四川</h3>
                                </li>
                                <li class="person-intro-detail">
                                    <h3>编写时间：2024年11月</h3>
                                </li>
                                <li class="person-intro-detail">
                                    <h3>站长：CrossFire
                                    </h3>
                                </li>
                            </ul>
                        </div>

                        <div class="column-container">
                            <ul class="column_box" id="like-box">
                                <li class="column-title">
                                    <span class=" at-sort b-b-ece fl">

                                        <a class=" choose c-666 fl" :class="{ active: activeTab === 'followers' }"
                                            @click="activeTab = 'followers'">
                                            关注
                                        </a>

                                        <a class="choose c-666 fl" :class="{ active: activeTab === 'followed' }"
                                            @click="activeTab = 'followed'">
                                            粉丝
                                        </a>
                                    </span>
                                </li>
                            </ul>

                            <div>

                                <div v-if="activeTab === 'followers'" class="follow_box">
                                    <div class="column_box follow_box_box" id="like-box" v-for="follow in followers"
                                        :key="follow.userId" @click="userDetail(follow.userId)">
                                        <li class="follow_li">
                                            <el-image id="person-img" style="width: 48px; height: 48px;"
                                                :src="follow.avatar"></el-image>
                                            <i v-if="follow.isMutual == 1" class="el-icon-connection"
                                                style="position: relative; left: -14px;"></i>
                                        </li>
                                        <li class="person-intro-detail gradient-text" style="text-align: center;">
                                            <div>{{ follow.nickname }}</div>
                                        </li>
                                    </div>
                                    <div class="more" style=" position: absolute;
                                top: 53%;
                                left: 80%;">
                                        <el-button type="text" @click="followerMore" :loading="isLoading"
                                            class="more-btn">
                                            更多...
                                        </el-button>
                                    </div>
                                </div>

                                <!-- 使用 v-if 判断当前是否为“粉丝”选项卡 -->
                                <div v-if="activeTab === 'followed'" class="follow_box">
                                    <div class="column_box follow_box_box" id="like-box" v-for="follow in followed"
                                        :key="follow.userId" @click="userDetail(follow.userId)">
                                        <li class="follow_li">
                                            <el-image id="person-img" style="width: 48px; height: 48px;"
                                                :src="follow.avatar"></el-image>
                                            <i v-if="follow.isMutual == 1" class="el-icon-connection"
                                                style="position: relative; left: -14px;"></i>
                                        </li>
                                        <li class="person-intro-detail gradient-text" style="text-align: center;">
                                            <div>{{ follow.nickname }}</div>
                                        </li>
                                    </div>

                                    <div class="more" style="position: absolute;top: 53%; left: 80%;">
                                        <el-button type="text" @click="followedMore" :loading="isLoading"
                                            class="more-btn">
                                            更多...
                                        </el-button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="column-container">
                            <ul class="column_box" id="like-box">
                                <li class="column-title">
                                    <span class="at-sort b-b-ece fl">
                                        <a class="at-sort-comment-a c-666 fl">OMT AI</a>
                                    </span>
                                </li>
                            </ul>


                            <div class="column_box follow_box_box" id="like-box">
                                <li class="follow_li" @click="showChat = true">
                                    <el-image id="person-img" src="/statics/images/ChatGPT.png"
                                        style="width: 48px; height: 48px;"></el-image>
                                </li>
                                <li class="person-intro-detail gradient-text" style="text-align: center;">
                                    <div>询问AI</div>
                                </li>
                            </div>
                        </div>
                    </div>
                </div>

            </el-container>
            <div class="menu-box" id="menu-box">
                <div class="menu-button" id="menu-button">
                    <div class="line-box">
                        <div class="line"></div>
                        <div class="line"></div>
                        <div class="line"></div>
                    </div>
                </div>
                <div>
                    <ul class="menu-list">
                        <li><a target="_blank" @click="toggleStatus(0)"><span>🧧搜索帖子</span></a></li>
                        <li><a target="_blank" @click="toggleStatus(1)"><span>📧发布帖子</span></a></li>

                    </ul>
                </div>
            </div>


            <el-dialog :visible.sync="dialogVisible[0]" width="30%">
                <p v-show="showError" style="color: red;">请输入关键字</p>
                <div id="search" style="display: block;">
                    <span class="search-s" style="display: flex; align-items: center;">
                        <el-input class="search-input" placeholder="请输入关键字" v-model="key" @keyup.enter="search">
                            <template #append>
                                <a class="search-icon fl" @click="search" href="javascript:void(0);">
                                </a>
                            </template>
                        </el-input>
                    </span>
                </div>
            </el-dialog>


            <el-dialog :visible.sync="dialogVisible[1]" width="30%">
                <el-form ref="newBlog" :model="newBlog" label-width="160px" :rules="newBlogRules">
                    <el-form-item label="标题" prop="title" disabled>
                        <el-input v-model="newBlog.title" placeholder="请输入标题"></el-input>
                    </el-form-item>
                    <el-form-item label="类型" prop="typeId">
                        <el-select v-model="newBlog.typeId" placeholder="请选择贴子类型">
                            <el-option v-for="tag in tags" :key="tag.blogTypeId" :label="tag.typeName"
                                :value="tag.blogTypeId"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="正文" prop="content">
                        <el-input v-model="newBlog.content" minlength="10" type="textarea"
                            placeholder="请输入正文"></el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="onSubmitNew('newBlog')">发布</el-button>
                    </el-form-item>


                </el-form>
            </el-dialog>


            <div v-if="showChat" class="chat-modal" @click.self="showChat = false">
                <div class="chat-container">
                    <div class="chat-window">
                        <div v-for="(message, index) in messages" :key="index" class="chat-message"
                            :class="{'message-left': message.isUser, 'message-right': !message.isUser}">
                            <div class="avatar">{{ message.isUser ? '自己' : 'AI' }}</div>
                            <div class="message-bubble">
                                {{ message.text }}
                            </div>
                        </div>
                        <div class="loading" v-if="loading">
                            <div style="display: flex;align-items: center;justify-content: center;">
                                <div class="loader"></div>
                                <div style="margin-left: 10px;font-weight: bold; color: #e64c87;">加载中</div>
                            </div>
                        </div>
                    </div>
                    <div class="chat-input">
                        <input v-model="userInput" @keydown.enter="sendMessage" placeholder="请输入您的问题......" />
                        <button @click="sendMessage">Send</button>
                    </div>
                </div>
            </div>
        </div>


        <footer class="footer">
            <div class="footer-line">Powered By Cross Fire • © 2024</div>
        </footer>

    </div>

    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@2.1.4/dist/jquery.min.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script type="text/javascript" src="/statics/js/sweetalert.min.js"></script>
    <script type="text/javascript" src="/statics/js/pace.min.js"></script>
    <script src="/statics/js/request.js"></script>
    <script>

        function getCookie(name) {
            let value = "; " + document.cookie;  
            let parts = value.split("; " + name + "="); 
            if (parts.length === 2) return parts.pop().split(";").shift();  
            return null;  
        }

        new Vue({
            el: '#app',
            data() {
                return {
                    showError: false,
                    userInput: '',
                    messages: [
                        { text: '你有什么需要问的问题吗?', isUser: false }
                    ],
                    loading: false,
                    showChat: false, 
                    topClicks: [],
                    blogsList: [],
                    form: { account: '', password: '', checkPassword: '' },
                    newBlogRules: {
                        title: [
                            { required: true, message: '请输入贴子标题', trigger: 'blur' },
                            { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                        ],
                        content: [
                            { required: true, message: '请输入正文', trigger: 'blur' },
                            { min: 10, max: 20000, message: '正文至少100字', trigger: 'blur' }
                        ],
                        typeId: [
                            { required: true, message: '请选择类型', trigger: 'blur' }
                        ],
                        seach: {
                            required: true, message: '请输入内容', trigger: 'blur'
                        }
                    },
                    personInfo: { name: '', avatar: '/statics/images/18908.png' },
                    newBlog: { title: '', content: '', typeId: null },
                    blogs: [],
                    pageParam: {
                        current: 1,
                        size: 5,
                        totalSize: 0
                    },
                    tags: [],
                    activeTab: 'followers',
                    followers: [],
                    followed: [],
                    activeIndex: '0',
                    key: '',
                    dialogVisible: [false, false],
                    drawer: false,
                    imageList: [],
                    uploadHeaders: {
                        'Authorization': 'Bearer ' + this.getToken()  // 在请求头中添加 token
                    }
                };
            },

            created() {
                this.load();
                this.initType();
                this.initUser();
                this.initFollowers();
                this.initFolloweds();
                request.post('/followInfo', (res) => {
                    this.follow.userId = res.userId;
                });
            },
            methods: {
                getToken() {
                    const token = document.cookie.replace(/(?:(?:^|.*;\s*)token\s*\=\s*([^;]*).*$)|^.*$/, "$1");
                    return token;
                },
                handlePageChange(page) {
                    this.pageParam.current = page;
                    this.load();
                },
                sendMessage() {
                    if (this.userInput.trim()) {
                        this.messages.push({ text: this.userInput, isUser: true });
                        this.simulateAIResponse(this.userInput);
                        this.userInput = '';
                    }
                },
                async simulateAIResponse(userText) {
                    this.loading = true;
                    try {
                        const token = getCookie('token');
                        if (!token) {
                            console.error('Token 不存在');
                            return;
                        }
                        const res = await axios.post("http://localhost:8080/test", {
                            question: this.userInput
                        }, {
                            headers: {
                                "Content-Type": "application/json",
                                "token": token
                            }
                        });
                        this.messages.push({
                            text: `AI回答内容: ${res.data.data}`,
                            isUser: false
                        });
                    } catch (error) {
                        console.error('AI接口请求失败', error);
                    } finally {
                        this.loading = false;
                    }
                },

                onSubmitNew(form) {
                    this.$refs[form].validate((valid) => {
                        if (valid) {
                            this.newBlog.author = this.personInfo.userId;
                            this.newBlog.readed = 0;
                            request.post("/addBlog", this.newBlog, (res) => {
                                if (res) {
                                    this.$message("发布成功");
                                    this.toggleStatus(1);
                                }
                            });
                        }
                    });
                },

                load() {
                    const data = {
                        typeId: this.activeIndex === '0' ? undefined : this.activeIndex,
                        key: this.key.trim() || undefined
                    };
                    console.log('Loading blogs with params:', this.pageParam, data);
                    this.initBlog(this.pageParam, data);
                },
                async initBlog(params, data) {
                    const url = '/blogs';
                    await request.post(url, data, params, (res) => {
                        if (res && res.list) {
                            this.blogs = res.list;
                            this.pageParam.totalSize = res.totalSize;
                            console.log('Total Size:', res.totalNumber);
                        }
                    });
                },


                async initType() {
                    await request.post("/types", (res) => { this.tags = res; });
                },

                async initUser() {
                    await request.post("/personalInfomation", (res) => {
                        this.personInfo = res;
                    });
                },

                async initFollowers() {
                    await request.post("/followers", (res) => {
                        this.followers = res;
                    });
                },

                async initFolloweds() {
                    await request.post("/followeds", (res) => {
                        this.followed = res;
                    });
                },

                followerMore() {
                    window.location = "/users/followers";
                },

                followedMore() {
                    window.location = "/users/followed";
                },

                userDetail(id) {
                    console.log(id);
                    window.location = "/personInfo/" + id;
                },

                toPersonInfo() {
                    if (this.personInfo.userId) {
                        window.location = '/personInfo/' + this.personInfo.userId;
                    } else {
                        console.error('User ID not available!');
                    }
                },
                toggleStatus(status) {
                    console.log(status);
                    console.log(!this.dialogVisible);
                    this.$set(this.dialogVisible, status, !this.dialogVisible[status]);
                },

                search() {
                    if (this.key.trim() === '') {
                        this.showError = true;
                        setTimeout(() => {
                            this.showError = false;
                        }, 2000);
                        return;
                    }

                    this.showError = false;
                    this.pageParam.current = 1;
                    this.blogs = [];
                    this.load();
                    this.dialogVisible[0] = false;
                },


                blogDetail(id) {
                    window.location = "/blog/" + id;
                }
            },

            filters: {

                dateFormate(date) {
                    return date.substring(0, 10);
                }
            }

        });
    </script>

    <script>
        new Vue({
            el: 'nav',
            data() {
                return {
                    personInfo: { userId: '' },
                    key: '',
                };
            },
            created() {
                this.initUser();
            },
            methods: {
                logout() {
                    window.sessionStorage.removeItem('token')
                    //document.cookie = `token=${res.token}; expires=${ data.getDate() -10 }`
                    let date = new Date()
                    date.setDate(date.getDate() - 1)
                    document.cookie = `token=""; expires=${date.toUTCString()}`
                    window.location = "/login"
                },
                async initUser() {
                    await request.post("/personalInfomation", (res) => {
                        this.personInfo = res;
                    });
                },
            }
        });
    </script>

    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const menuBox = document.querySelector('.menu-box');
            const menuButton = document.querySelector('.menu-button');

            menuButton.addEventListener('click', function () {
                menuBox.classList.toggle('active');
            });

            let isDragging = false;
            let startX, startY, initialX, initialY;

            menuBox.addEventListener('mousedown', (e) => {
                isDragging = true;
                startX = e.clientX;
                startY = e.clientY;
                initialX = menuBox.offsetLeft;
                initialY = menuBox.offsetTop;
                menuBox.style.cursor = 'grabbing';

                const onMouseMove = (e) => {
                    if (isDragging) {
                        const dx = e.clientX - startX;
                        const dy = e.clientY - startY;
                        menuBox.style.left = `${initialX + dx}px`;
                        menuBox.style.top = `${initialY + dy}px`;
                    }
                };

                const onMouseUp = () => {
                    isDragging = false;
                    menuBox.style.cursor = 'grab';
                    document.removeEventListener('mousemove', onMouseMove);
                    document.removeEventListener('mouseup', onMouseUp);
                };

                document.addEventListener('mousemove', onMouseMove);
                document.addEventListener('mouseup', onMouseUp);
            });
        });

    </script>

</body>

</html>